package com.tianji.aigc.service.impl;

import cn.hutool.core.util.IdUtil;
import com.tianji.aigc.ChatMemory.RedisChatMemory;
import com.tianji.aigc.config.SessionProperties;
import com.tianji.aigc.entity.ChatSession;
import com.tianji.aigc.vo.MessageVO;
import com.tianji.aigc.vo.SessionVO;
import com.tianji.aigc.mapper.ChatSessionMapper;
import com.tianji.aigc.service.IChatSessionService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tianji.common.exceptions.BadRequestException;
import com.tianji.common.exceptions.BizIllegalException;
import com.tianji.common.utils.UserContext;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.ai.chat.messages.Message;
import org.springframework.ai.chat.messages.MessageType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.Collections;
import java.util.List;

/**
 * <p>
 * 对话session 服务实现类
 * </p>
 *
 * @author xyc
 * @since 2025-09-02
 */
@Service
public class ChatSessionServiceImpl extends ServiceImpl<ChatSessionMapper, ChatSession> implements IChatSessionService {

    @Autowired
    private SessionProperties sessionProperties;
    @Override
    public SessionVO createSession(Integer num) {
        //1.生成会话ID
        String sessionId = IdUtil.fastSimpleUUID();

        //2.保存会话历史
        ChatSession chatSession = ChatSession.builder().sessionId(sessionId)
                .userId(UserContext.getUser()).build();
        this.save(chatSession);

        //3.随机取出3个热门问题
        List<SessionVO.Example> examples = sessionProperties.getExamples();
        Collections.shuffle(examples);
        List<SessionVO.Example> exampleList = examples.stream().limit(num).toList();
        //4.封装响应结果
        SessionVO sessionVO = SessionVO.builder()
                .sessionId(sessionId)
                .title(sessionProperties.getTitle())
                .describe(sessionProperties.getDescribe())
                .examples(exampleList)
                .build();

        return sessionVO;
    }

    @Override
    public List<SessionVO.Example> getHotQuestions(@RequestParam(value = "n", defaultValue = "3") Integer num) {
        // 随机取出3个热门问题
        List<SessionVO.Example> examples = sessionProperties.getExamples();
        Collections.shuffle(examples);
        List<SessionVO.Example> exampleList = examples.stream().limit(num).toList();
        return exampleList;
    }

    @Autowired
    private RedisChatMemory redisChatMemory;

    /**
     * 获取会话详情
     *
     * @param sessionId
     * @return
     */
    @Override
    public List<MessageVO> messageList(String sessionId) {
        //判断是会话ID是否存在
        ChatSession chatSession = this.lambdaQuery().eq(ChatSession::getSessionId, sessionId).one();
        if(chatSession==null) {
            throw new BadRequestException("会话不存在");
        }
        List<Message> messageList = redisChatMemory.get(UserContext.getUser() + ":" + sessionId, 1000);
        return messageList.stream()
                //只获取用户消息和助手消息
                .filter(m->m.getMessageType().equals(MessageType.USER) || m.getMessageType().equals(MessageType.ASSISTANT))
                .map( m-> MessageVO.builder().type(m.getMessageType()).content(m.getText()).build()).toList();
    }
}
